package com.mlnx.device.service.impl;

import com.mlnx.common.entity.Response;
import com.mlnx.common.utils.MyLog;
import com.mlnx.device.pojo.dto.AutoDetectCmdDto;
import com.mlnx.device.pojo.dto.AutoDetectTask;
import com.mlnx.device.pojo.dto.SynData;
import com.mlnx.device.service.XmBpDeviceService;
import com.mlnx.device.session.manager.MutilDeviceSessionManager;
import com.mlnx.device.syn.SynDataManage;
import com.mlnx.device.util.CmdUtils;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Service
public class XmBpDeviceServiceIml implements XmBpDeviceService {

    @Autowired
    private XmBpControllService xmBpControllService;

    @Autowired
    private MutilDeviceSessionManager sessionManager;

    private MyLog log = MyLog.getLog(this.getClass());

    ExecutorService executor = Executors.newFixedThreadPool(20);

    private void runSendTask(AutoDetectTask task) {
        try {

            AutoDetectCmdDto autoDetectCmd = task.getAutoDetectCmd();
            boolean success = xmBpControllService.sendAutoDetect(autoDetectCmd);

            if (success) {
                task.getResponseDeferredResult().setResult(new Response());
            } else {
                task.getResponseDeferredResult().setResult(new Response("0001", "设置失败"));
                Channel channel = sessionManager.getChannel(autoDetectCmd.getDeviceId());
                sessionManager.removeSession(channel);
                log.info("无法向血压计发送指令，移除该血压计:{}", autoDetectCmd.getDeviceId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public DeferredResult<Response> setDetectTime(AutoDetectCmdDto autoDetectCmd) {
        DeferredResult<Response> deferredResult = new DeferredResult<>();

        // 1、判断设备是否在线
        Channel channel = sessionManager.getChannel(autoDetectCmd.getDeviceId());
        if (channel == null) {
            deferredResult.setResult(new Response("0002", "设备不在线"));
            log.error("设备不在线");
            return deferredResult;
        }
        AutoDetectTask detectTask = new AutoDetectTask();
        detectTask.setAutoDetectCmd(autoDetectCmd);
        detectTask.setResponseDeferredResult(deferredResult);

        executor.submit(new Runnable() {
            @Override
            public void run() {
                runSendTask(detectTask);
            }
        });

        return deferredResult;
    }

    @Override
    public DeferredResult<Response> setState(AutoDetectCmdDto autoDetectCmd) {
        DeferredResult<Response> deferredResult = new DeferredResult<>();
        // 1、判断设备是否在线
        Channel channel = sessionManager.getChannel(autoDetectCmd.getDeviceId());
        if (channel == null) {
            deferredResult.setResult(new Response("0002", "设备不在线"));
            log.error("设备不在线");
            return deferredResult;
        }
        AutoDetectTask detectTask = new AutoDetectTask();
        detectTask.setAutoDetectCmd(autoDetectCmd);
        detectTask.setResponseDeferredResult(deferredResult);
        executor.submit(new Runnable() {
            @Override
            public void run() {
                runSendTask(detectTask);
            }
        });

        return deferredResult;
    }

    @Override
    public DeferredResult<Response> setDetect(AutoDetectCmdDto autoDetectCmd) {
        DeferredResult<Response> deferredResult = new DeferredResult<>();
        // 1、判断设备是否在线
        Channel channel = sessionManager.getChannel(autoDetectCmd.getDeviceId());
        if (channel == null) {
            deferredResult.setResult(new Response("0002", "设备不在线"));
            log.error("设备不在线");
            return deferredResult;
        }
        AutoDetectTask detectTask = new AutoDetectTask();
        detectTask.setAutoDetectCmd(autoDetectCmd);
        detectTask.setResponseDeferredResult(deferredResult);
        executor.submit(new Runnable() {
            @Override
            public void run() {
                runSendTask(detectTask);
            }
        });

        return deferredResult;
    }

    /**
     * 矫正时间 清空记录 重启编程
     *
     * @param autoDetectCmd
     * @return
     */
    @Override
    public DeferredResult<Response> setRectify(AutoDetectCmdDto autoDetectCmd) {
        DeferredResult<Response> deferredResult = new DeferredResult<>();
        // 1、判断设备是否在线
        Channel channel = sessionManager.getChannel(autoDetectCmd.getDeviceId());
        if (channel == null) {
            deferredResult.setResult(new Response("0002", "设备不在线"));
            log.error("设备不在线");
            return deferredResult;
        }
        AutoDetectTask detectTask = new AutoDetectTask();
        detectTask.setAutoDetectCmd(autoDetectCmd);
        detectTask.setResponseDeferredResult(deferredResult);
        executor.submit(new Runnable() {
            @Override
            public void run() {

                try {
                    runSendTask(detectTask);
                    log.info("矫正时间");
                    Thread.sleep(1000);
                    channel.writeAndFlush(Unpooled.copiedBuffer(CmdUtils.beginCrc));
                    Thread.sleep(1000);
                    channel.writeAndFlush(Unpooled.copiedBuffer(CmdUtils.delRecordCrc));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });

        return deferredResult;
    }

    /**
     * 同步数据
     *
     * @param autoDetectCmd
     * @return
     */
    @Override
    public DeferredResult<Response> synData(AutoDetectCmdDto autoDetectCmd) {
        DeferredResult<Response> deferredResult = new DeferredResult<>();
        // 1、判断设备是否在线
        Channel channel = sessionManager.getChannel(autoDetectCmd.getDeviceId());
        if (channel == null) {
            deferredResult.setResult(new Response("0002", "设备不在线"));
            log.error("设备不在线");
            return deferredResult;
        }

        SynData synData = new SynData();
        synData.setResponseDeferredResult(deferredResult);
        synData.setOverTime(0);
        synData.setCurrentSign(true);
        SynDataManage.getInstance().add(autoDetectCmd.getDeviceId(), synData);

        return deferredResult;
    }
}
